<template>
  <el-drawer
    :title="drawerTitle[drawerType]"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="clearDialog"
    custom-class="tag-drawer user-drawer"
    v-drawerResize
  >
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
          <h4 class="type-title">
            <div class="icon-box"><icon-svg name="iconBase"></icon-svg></div>
            <span>基本信息</span>
          </h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="登录名" prop="loginUname">
                <el-input
                  placeholder="请输入登录名"
                  :readonly="!userNameEditable"
                  v-model="editForm.loginUname"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工号" prop="empId">
                <el-input placeholder="请输入工号" :readonly="!editable" v-model="editForm.empId"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属公司" prop="compId">
                <tag-tree-selection
                  title="所属公司"
                  :data="compTreeList"
                  :treeProps="compTreeProps"
                  :initId="editForm.compId"
                  :editable="editable"
                  @confirm="id => (editForm.compId = id)"
                ></tag-tree-selection>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="deptId">
                <tag-tree-selection
                  title="所属部门"
                  :placeholder="'选择公司后才能选择部门'"
                  :data="deptTreeList"
                  :treeProps="deptTreeProps"
                  :initId="editForm.deptId"
                  :editable="!!editForm.compId"
                  @confirm="id => (editForm.deptId = id)"
                ></tag-tree-selection>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号" prop="userMobile">
                <el-input placeholder="请输入手机号" :readonly="!editable" v-model="editForm.userMobile"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="userEmail">
                <el-input placeholder="请输入邮箱" :readonly="!editable" v-model="editForm.userEmail"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职位" prop="userPost">
                <el-input placeholder="请输入职位" :readonly="!editable" v-model="editForm.userPost"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <h4 class="type-title">
            <div class="icon-box"><icon-svg name="iconBase"></icon-svg></div>
            <span>详细信息</span>
          </h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="cnName">
                <el-input placeholder="请输入姓名" :readonly="!editable" v-model="editForm.cnName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="英文名" prop="enName">
                <el-input placeholder="请输入英文名" :readonly="!editable" v-model="editForm.enName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户昵称" prop="nname">
                <el-input placeholder="请输入用户昵称" :readonly="!editable" v-model="editForm.nname"></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
            <el-form-item label="是否系统用户" prop="sysUser">
              <el-radio-group v-model="editForm.sysUser">
                <el-radio v-for="dict in $dictList('auth_user_type')" :key="dict.key" :label="dict.key">{{
                  dict.value
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          </el-row>
          <!-- <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注信息" prop="cmntStr">
                <el-input
                  type="textarea"
                  placeholder="请输入备注信息，最大不能超过100个字符"
                  v-model="editForm.cmntStr"
                  :readonly="!editable"
                  :rows="3"
                  resize="none"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="clearDialog">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-drawer>
</template>

<script>
import tagTreeSelection from '@/components/tag-tree-selection'
import utils from '@/plugins/utils'
export default {
  components: {
    tagTreeSelection
  },
  data() {
    let mobileValidator = (rule, value, callback) => {
      if (value) {
        if (!/^1[0-9]{10}$/.test(value)) callback(new Error('请输入正确的手机号'))
        else callback()
      } else callback()
    }
    return {
      editable: true,
      drawerVisible: false,
      drawerType: 'add',
      drawerTitle: {
        add: '新增',
        edit: '编辑'
      },
      userId: '',
      userStatus: '',
      editForm: {
        compId: '',
        deptId: '',
        empId: '',
        cnName: '',
        enName: '',
        loginUname: '',
        nname: '',
        userMobile: '',
        userEmail: '',
        userPost: '',
        sysUser: 0,
        avatarUrl: '',
        cmntStr: ''
      },
      editFormRules: {
        compId: [{ required: true, message: '公司不能为空', trigger: 'change' }],
        empId: [
          { required: true, message: '工号不能为空', trigger: 'blur' },
          { max: 20, message: '工号不能超过20个字符', trigger: 'blur' }
        ],
        deptId: [{ required: true, message: '部门不能为空', trigger: 'change' }],
        loginUname: [
          { required: true, message: '登录名不能为空', trigger: 'blur' },
          { max: 20, message: '登录名不能超过20个字符', trigger: 'blur' }
        ],
        nname: [{ max: 20, message: '用户昵称不能超过20个字符', trigger: 'blur' }],
        userMobile: [{ validator: mobileValidator, trigger: 'blur' }],
        userEmail: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
        userPost: [
          // { required: true, message: '职位不能为空', trigger: 'blur' },
          { max: 30, message: '职位不能超过30个字符', trigger: 'blur' }
        ],
        cnName: [{ max: 20, message: '姓名不能超过20个字符', trigger: 'blur' }],
        enName: [{ max: 20, message: '英文名不能超过20个字符', trigger: 'blur' }],
        cmntStr: [{ max: 100, message: '备注信息不能超过100个字符', trigger: 'blur' }]
      },
      compTreeList: [],
      compTreeProps: {
        title: '所属公司',
        children: '_children',
        label: 'compNm',
        id: 'compId'
      },
      deptTreeList: [],
      deptTreeProps: {
        title: '所属部门',
        children: '_children',
        label: 'deptNm',
        id: 'deptId'
      },
      userNameEditable: true
    }
  },
  watch: {
    'editForm.compId'(val) {
      if (val.toString()) this.getDeptList(val)
      else {
        this.deptTreeList = []
        this.editForm.deptId = ''
      }
    }
  },
  methods: {
    getCompList() {
      return new Promise((rosolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('auth/authCompMgr/list'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.compTreeList = utils.arrayToTree(data.data, {
              id: 'compId',
              pid: 'parentCompId',
              mainSort: 'treeLevel'
            })
            rosolve()
          } else {
            this.$message.error('获取公司列表失败！')
            reject()
          }
        })
      })
    },
    getDeptList(compId) {
      let dept = this.editForm.deptId
      this.editForm.deptId = ''
      this.$ajax({
        url: this.$ajax.setUrl('auth/authDeptMgr/compId/' + compId),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.deptTreeList = utils.arrayToTree(data.data, {
            id: 'deptId',
            pid: 'parentDeptId',
            mainSort: 'treeLevel'
          })
          this.editForm.deptId = dept
        } else {
          this.$message.error('获取部门列表失败！')
        }
      })
    },
    getRoleList() {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('sys/sysRoleMgr/list'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.roleList = data.data
            resolve()
          } else {
            this.$message.error('获取角色列表失败！')
            reject()
          }
        })
      })
    },
    showDrawer(type, data) {
      if (type === 'edit') this.userNameEditable = false
      else this.userNameEditable = true
      this.drawerType = type
      Promise.all([this.getCompList(), this.getRoleList()]).then(() => {
        switch (type) {
          case 'add':
            this.editable = true
            this.drawerVisible = true
            break
          case 'edit':
            this.editable = true
            this.getUserDetail(data)
            break
        }
      })
    },
    submit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let params = {
            deptId: this.editForm.deptId,
            empId: this.editForm.empId,
            cnName: this.editForm.cnName,
            enName: this.editForm.enName,
            loginUname: this.editForm.loginUname,
            nname: this.editForm.nname,
            userId: this.userId,
            userMobile: this.editForm.userMobile,
            userEmail: this.editForm.userEmail,
            userPost: this.editForm.userPost,
            sysUser: this.editForm.sysUser,
            avatarUrl: this.editForm.avatarUrl,
            cmntStr: this.editForm.cmntStr
          }
          this.confirmSUbmit(params)
        }
      })
    },
    confirmSUbmit(params) {
      this.$ajax({
        url: this.$ajax.setUrl('auth/authUserMgr'),
        method: this.drawerType === 'add' ? 'post' : 'put',
        data: this.$ajax.setData(params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.clearDialog()
          this.$emit('refresh')
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getUserDetail(scope) {
      this.$ajax({
        url: this.$ajax.setUrl('auth/authUserMgr/' + scope.userId),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.userId = data.data.userId || ''
          this.userStatus = data.data.userStatus
          this.editForm.compId = data.data.compId || ''
          this.editForm.deptId = data.data.deptId || ''
          this.editForm.empId = data.data.empId || ''
          this.editForm.cnName = data.data.cnName || ''
          this.editForm.enName = data.data.enName || ''
          this.editForm.loginUname = data.data.loginUname || ''
          this.editForm.nname = data.data.nname || ''
          this.editForm.userMobile = data.data.userMobile || ''
          this.editForm.userEmail = data.data.userEmail || ''
          this.editForm.userPost = data.data.userPost || ''
          this.editForm.sysUser = data.data.sysUser ? 1 : 0
          this.editForm.avatarUrl = data.data.avatarUrl || ''
          // this.editForm.cmntStr = data.data.cmntStr || ''
          this.drawerVisible = true
        } else {
          this.$message.error('获取用户信息失败！')
        }
      })
    },
    clearDialog() {
      this.userId = ''
      this.userStatus = ''
      this.editForm.compId = ''
      this.editForm.deptId = ''
      this.editForm.empId = ''
      this.editForm.cnName = ''
      this.editForm.enName = ''
      this.editForm.loginUname = ''
      this.editForm.nname = ''
      this.editForm.userPost = ''
      this.editForm.sysUser = 0
      this.editForm.avatarUrl = ''
      this.editForm.cmntStr = ''
      this.editForm.userMobile = ''
      this.editForm.userEmail = ''
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
      this.drawerVisible = false
    }
  }
}
</script>

<style lang="scss">
.user-drawer {
  .sys-user-table {
    margin-bottom: 20px;
    td,
    th {
      padding: 5px 0;
    }
  }
}
</style>
